package pro.lepers.portfolio.view.misc {
	import flash.filters.BlurFilter;
	import flash.geom.ColorTransform;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	/**
	 * @author plepers
	 */
	public class PaperNoise extends BitmapData {

		
		public function get color () : uint {
			return _color;
		}
		
		public function set color (color : uint) : void {
			_color = color;
		}
		
		
		
		
		public function PaperNoise ( width : int, height : int, transparent : Boolean = false, color : uint = 0 ) {
			_color = color;
			super( width, height, transparent , color );
			_createRandomBlobs();
			_draw( );
		}

		private function _draw () : void {
			
			fillRect( rect, _color );
			
			noise( Math.random() * 1000, 200, 0xFF, 7, true );
			colorTransform(rect, new ColorTransform(1,1,1, .2) );
			//applyFilter( this, rect, new Point(), new BlurFilter(1,1,1) );
			 
			var numBlob : int = (width * height) / 10000 * _density;
			
			var bpos : Point = new Point();
			var c : int = 0;
			for (var i : int = 0; i < numBlob; i++) {
				bpos.x = Math.random() * width;
				bpos.y = Math.random() * height;
				copyPixels( _blobs[c], _blobs[c].rect, bpos, null, null, true );
				
				c++;
				if( c == _blobs.length ) c = 0;
			}
		}

		private function _createRandomBlobs() : void {
			if( _blobs ) return;
			_blobs = new Vector.<BitmapData>( NUM_BLOBS , true );
			
			var blob : BitmapData;
			var bShape : Shape = new Shape();
			var graphics : Graphics = bShape.graphics;
			var ca : Number;
			var d : Number;
			var mpi : Number = Math.PI * 2 / BLOB_SHAPE_CUTS;
			var bounds : Rectangle;
			var m : Matrix = new Matrix();
			
			for (var i : int = 0; i < NUM_BLOBS ; i++) {
				
				graphics.beginFill( 0, _noiseStrenght * Math.random() );
				
				for( var j : int = 0; j < BLOB_SHAPE_CUTS; j++ ) {
					ca = mpi*j;
					d = Math.random( ) * _noiseSize;
					if( j == 0 ) graphics.moveTo( d*Math.cos( ca ), d*Math.sin( ca ) );
					else graphics.lineTo( d*Math.cos( ca ), d*Math.sin( ca ) );
				}
				
				bounds = bShape.getBounds( bShape );
				m.tx = -bounds.x;
				m.ty = -bounds.y;
				
				blob = new BitmapData( bounds.width, bounds.height , true, 0 );
				blob.draw( bShape , m );
				
				
				graphics.clear();
				_blobs[ i ] = blob;
			}
		}

		private var _blobs : Vector.<BitmapData>;

		private var _color : uint;
		
		private var _noiseSize : Number = 2.4;
		
		private var _density : int = 25; // blob per 10000px
		
		private var _noiseStrenght : Number = .1;
		
		private static const NUM_BLOBS : int = 32;
		private static const BLOB_SHAPE_CUTS : int = 8;
	}
}
